using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;

namespace Domain
{
    internal class NHibernateHelper
    {
        private static NHibernateHelper instance;
        private ISessionFactory factory;

        public static NHibernateHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new NHibernateHelper();
                }
                return instance;
            }
        }

        private NHibernateHelper()
        {
            factory = new Configuration().Configure().BuildSessionFactory();
        }

        public ISessionFactory SessionFactory
        {
            get { return factory; }
        }

        public ISession OpenSession()
        {
            return factory.OpenSession();
        }

        public ISession CurrentSession
        {
            get { return NHibernateHttpModule.CurrentSession; }
        }

        public static String ConvertDateTime(DateTime dateTime)
        {
            return dateTime.ToString("yyyy-MM-dd HH:mm:ss");
        }

        public static string ConvertToCSV(List<int> intList)
        {
            return string.Join(
                ",",
                intList.ConvertAll<string>(
                    delegate(int from) { return from.ToString(); }
                ).ToArray()
            );
        }

        public static T GetById<T>(object id)
        {
            return Instance.CurrentSession.Get<T>(id);
        }

        public static IList<T> GetAll<T>()
        {
            return Instance.CurrentSession.CreateCriteria(typeof(T)).List<T>();
        }

        public static IList<T> ListQuery<T>(string query)
        {
            return Instance.CurrentSession.CreateQuery(query).List<T>();
        }

        public static IList<T> QueryPaged<T>(string query, int page, int countPerPage)
        {
            IQuery queryObj = Instance.CurrentSession.CreateQuery(query);
            queryObj.SetMaxResults(countPerPage);
            queryObj.SetFirstResult((page - 1) * countPerPage);
            return queryObj.List<T>();
        }

        public static int CountQuery(string query)
        {
            return (int)Instance.CurrentSession.CreateQuery(query).UniqueResult<long>();
        }
    }
}
